/**
 * Created by Mic on 16/2/22.
 */

var pomelo = require('pomelo');
var mem = pomelo.app.get('memclient');
var logger = require('pomelo-logger').getLogger(__filename);
var async = require('async');
var dispatcher = require('../../../util/dispatcher');
var ChannelUtil = require('../../../util/channelUtil');
var consts = require('../../../consts/consts');

module.exports = function (app) {
    return new HallRemote(app);
};

var HallRemote = function (app) {
    this.app = app;
};
var handler = HallRemote.prototype;

handler.quitHall = function (player, serverId, next) {
    if (player.hasOwnProperty('player')) {
        player = player.player;
    }
    getMem(player.uuid, function (data) {
        if (!!data) {
            logger.info('从房间中退出 ', data);
            data = data.serverId;
            pomelo.app.rpc.room.roomRemote.exitRoom({serverId: data}, player, serverId, next);
        } else {
            next();
        }
    });
};
handler.add = function (player, channelName, cb) {
    logger.info('Global Channel add ' + player.uuid);
    var sid = getSidByUid(player.uuid, this.app);
    var channel = this.app.get('channelService').getChannel(channelName, true);
    if (!!channel) {
        channel.add(player.uuid, sid);

        var self = this;

        async.parallel([function (callback) {
            cb(null, 200);
        }, function (callback) {
            checkFirstLogin(player, function (flag) {
                //目前移除了领取救济金的模块

                //if (flag == consts.Event.GetHelpMoney) {
                //    self.helpMoney(player,function(){});
                //} else if (flag == consts.Event.FirstLogin) {
                //    //self.pushMsgByUid(player, ChannelUtil.getGlobalChannelName(), 'on_login', {msg: '签到'});
                //} else if (flag == consts.Event.LoginAndHelp) {
                //    self.helpMoney(player,function(){});
                //    //self.pushMsgByUid(player, ChannelUtil.getGlobalChannelName(), 'on_login', {msg: '签到'});
                //} else if (flag == consts.Event.CannotGetHelp) {
                //    self.pushMsgByUid(player, ChannelUtil.getGlobalChannelName(), 'on_goShop', {msg: '领取次数达到上限,请去商店充值!'});
                //}
            });
        }], function (err, result) {
        });
    }
};


handler.helpMoney = function (player, cb) {
    var self = this;
    cb({code: 500});
    //this.getHelpMoney(player, function (err, data) {
    //    var msg = null;
    //    if (data.code == consts.Code.Ok) {
    //        msg = {counts: data.counts, code: 200,money:data.money};
    //        self.pushMsgByUid(player, ChannelUtil.getGlobalChannelName(), 'on_helpMoney', msg);
    //        cb(data);
    //    } else if (data.code == consts.Code.Fail) {
    //        logger.fatal('今日的救济金已经领完,请充值!');
    //        msg = {code: 500};
    //        self.pushMsgByUid(player, ChannelUtil.getGlobalChannelName(), 'on_helpMoney', msg);
    //        cb({code: 500});
    //    }
    //});
};

handler.kick = function (player, channelName, cb) {
    var sid = getSidByUid(player.uuid, this.app);
    var channel = this.app.get('channelService').getChannel(channelName, true);
    if (channel) {
        channel.leave(player.uuid, sid);
        logger.info(channel.getMembers());
    }
    cb(null, 200);
};
handler.pushMsgByUid = function (player, channelName, route, msg) {
    var channel = this.app.get('channelService').getChannel(channelName, true);
    var sid = getSidByUid(player.uuid, this.app);
    if (channel) {
        this.app.get('channelService').pushMessageByUids(route, msg, [{uid: player.uuid, sid: sid}]);
    }
};

//领取救济金
handler.getHelpMoney = function (playerInfo, next) {
    //userDao.getUserByUuid(playerInfo, function (err, code, res) {
    //pomelo.rpc.interface.interfaceRemote.getUserBySid(playerInfo.uuid, function (err, code, res) {
    //    if (code == 200) {
    //        var player = res[0];
    //        var getMoneyCounts = player.getMoneyCounts;
    //        if (getMoneyCounts < 4) {
    //            getMoneyCounts++;
    //            logger.debug('这是今日第 ' + getMoneyCounts + ' 次领取救济金 ');
    //            var money = player.coins + consts.Player.Money;
    //            //userDao.updateGetMoneyCountsAndMoney(player.uuid, getMoneyCounts, money, function (data) {
    //            pomelo.rpc.interface.interfaceRemote.updateGetMoneyCountsAndMoney(player.uuid, getMoneyCounts, money, function (data) {
    //                next(null, {code: consts.Code.Ok, counts: getMoneyCounts--, money: money});
    //            });
    //        } else {
    //            logger.debug('今日救济金领取完毕!');
    //            next(null, {code: consts.Code.Fail});
    //        }
    //    }
    //});
};

var getMem = function (uuid, cb) {
    mem.get(uuid, function (err, data) {
        logger.info('get mem ' + data);
        cb(data);
    });
};


var checkFirstLogin = function (player, cb) {
    cb();
    //先拉取上次的登陆时间 然后再写入现在的登录时间
    //var date = new Date();
    //date.setISO8601(player.lastLoginTime);
    //var loginDate = date.format('yyyy-MM-dd');
    //var curTime = new Date().format("yyyy-MM-dd");
    //var getMoneyCounts = player.getMoneyCounts;
    //var coins = player.coins;
    //
    //logger.info('>>>>>>>' + loginDate + ' -  ' + curTime);

    //今天首次登录 可以做一系列的事情
    //if (loginDate != curTime) {
    //    pomelo.rpc.interface.interfaceRemote.updateLoginTime(player.uuid, curTime,0, function (err,data) {
    //        //userDao.updateLoginTime(player.uuid, curTime, 0, function (err, data) {
    //            if (coins < consts.Player.Money) {
    //                cb(consts.Event.LoginAndHelp);
    //            } else {
    //                cb(consts.Event.FirstLogin);
    //            }
    //        });
    //} else {
    //    if (getMoneyCounts < 4 && coins < consts.Player.Money) {
    //        cb(consts.Event.GetHelpMoney);
    //    } else if (getMoneyCounts == 4 && coins < consts.Player.Money) {
    //        cb(consts.Event.CannotGetHelp)
    //    } else {
    //        cb(false);
    //    }
    //}
};

var getSidByUid = function (uid, app) {
    var connector = dispatcher.dispatch(uid, app.getServersByType('connector'));
    if (connector) {
        return connector.id;
    }
    return null;
};

Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

Date.prototype.setISO8601 = function (string) {
    var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
        "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
        "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
    if (string) {
        var d = string.match(new RegExp(regexp));
        var offset = 0;
        var date = new Date(d[1], 0, 1);

        if (d[3]) {
            date.setMonth(d[3] - 1);
        }
        if (d[5]) {
            date.setDate(d[5]);
        }
        if (d[7]) {
            date.setHours(d[7]);
        }
        if (d[8]) {
            date.setMinutes(d[8]);
        }
        if (d[10]) {
            date.setSeconds(d[10]);
        }
        if (d[12]) {
            date.setMilliseconds(Number("0." + d[12]) * 1000);
        }
        if (d[14]) {
            offset = (Number(d[16]) * 60) + Number(d[17]);
            offset *= ((d[15] == '-') ? 1 : -1);
        }
        offset -= date.getTimezoneOffset();
        var time = (Number(date) + (offset * 60 * 1000));
        this.setTime(Number(time));
    }
};